package com.godme.concurrent.util;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
    static final Random random  = new Random();


    static class MyThread extends Thread{

        private final CountDownLatch latch;

        public MyThread(String name, CountDownLatch latch){
            super(name);
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                System.err.println(getName() +" : running");
                sleep(random.nextInt(2000));
                System.err.println(getName() + " : done");
                latch.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(5);
        for (int i = 0; i < 5; i++) {
            new MyThread("thread-"+i, latch).start();
        }
        latch.await();
    }
}
